package com.carrot.framework.holder;

import java.util.Optional;

/**
 * 用户上下文
 * @author liuhongzhen
 */
public final class SystemContextHolder {

    /**
     * 存储上下文信息
     */
    public static final ThreadLocal<String> THREAD_LOCAL = new ThreadLocal<>();

    /**
     * 获取当前系统标识
     * 推荐用法,避免空指针:
     * String tag = UserContextHolder.getSystemTag().orElseThrow(() -> new BusinessException("提示未登录即可"));
     *
     * @return Optional<String>
     */
    public static Optional<String> getSystemTag() {
        return Optional.ofNullable(THREAD_LOCAL.get());
    }


    public static void setSystemTag(String systemTag) {
        if (THREAD_LOCAL.get() == null) {
            THREAD_LOCAL.set(systemTag);
        }
    }

    public static void clear() {
        THREAD_LOCAL.remove();
    }

    /**
     * 私有化构造函数
     */
    private SystemContextHolder(){}

}
